#include "TextureParser.h"
#include "..\utils\Log.h"
#include "..\utils\PlainTextReader.h"
#include "..\base\Engine.h"
#include "..\game\World.h"
#include "..\content\Texture.h"

namespace ds {

bool TextureParser::isSupported(const std::string& fileEnding) const {
	bool ret = false;
	if ( fileEnding == ".png" ) {
		ret = true;
	}
	return ret;
}

ResourceDeclaration* TextureParser::loadTextFile(const ResourceFile& resourceFile) {
	LOGC(logINFO,"TextureParser") << "Adding texture declaration for file " << resourceFile.fqName;
	TextureDecl* td = new TextureDecl(resourceFile.fqName);
	return td;
}

void TextureParser::createResource(ResourceDeclaration* declaration) {
	TextureDecl* td = static_cast<TextureDecl*>(declaration);
	std::string filename(td->getName());
	size_t pos = filename.find_last_of("\\");
	std::string textureName = filename.substr(pos+1);
	pos = textureName.find(".");
	textureName = textureName.substr(0,pos);
	textureName[0] = toupper(textureName[0]);
	LOGC(logINFO,"TextureParser") << "file : " << filename;
	LOGC(logINFO,"TextureParser") << "name: " << textureName;
	std::string texName = textureName + "Texture";
	ResourceHandle rh = gEngine->getResourceManager().createTexture(texName.c_str(),td->getName().c_str());
	std::string matName = textureName + "Material";
	gEngine->getResourceManager().createMaterial(matName.c_str(),rh,true);	
}
/*
bool TextureParser::readTextFile(const char* name,PAKWriter& writer) {
				
	writer.writeInt(getType());
	Texture* tex = gEngine->getResourceManager().getTextureByName(textureName+"Texture");
	if ( tex == 0 ) {
		LOG(logERROR) << "texture " << textureName << " not found";
		return false;
	}
	writer.writeString(textureName+"Texture");
	tex->lock();
	int w = tex->getWidth();
	writer.writeInt(w);
	int h = tex->getHeight();
	writer.writeInt(h);
	LOG(logINFO) << "saving texture to binary w: " << w << " h: " << h;
	for ( int x = 0; x < w; ++x ) {
		for ( int y = 0; y < h; ++y ) {
			for ( int o = 0; o < 4; ++o ) {
				uchar color = tex->getColor(x,y,o);
				writer.writeUChar(color);
			}
		}
	}
	tex->unlock();
	return true;
}
*/
/*
bool TextureParser::readBinary(PAKReader& reader) {
	std::string name = reader.readString();
	int w = reader.readInt();
	int h = reader.readInt();
	LOG(logINFO) << "reading texture " << name << " width " << w << " height " << h;
	Texture* tex = new Texture(name);
	tex->createTexture(w,h);
	ResourceHandle rh = gEngine->getResourceManager().createTexture(name,tex);
	gEngine->getResourceManager().createMaterial(name+"Material",rh,true);			
	tex->lock();		
	uchar color[4];
	for ( int x = 0; x < w; ++x ) {
		for ( int y = 0; y < h; ++y ) {
			for ( int o = 0; o < 4; ++o ) {
				tex->setColor(x,y,o,reader.readUChar());
			}
		}
	}
	tex->unlock();
	return true;
}
*/
}
